package com.service.qm;

import java.io.IOException;
import java.rmi.ServerException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.qm.PartsDetailDao;
import com.dao.qm.ProcessDao;
import com.model.qm.PartsDetailModel;
import com.model.qm.ProcessModel;
import com.model.sys.SysUser;
import com.service.external.sap.SapPartsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.dao.qm.PartsDao;
import com.model.qm.PartsModel;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

@Service
public class PartsService {
	static final Logger logger = LoggerFactory.getLogger(PartsService.class);

	@Autowired
	PartsDao partsDao;
	@Autowired
	ProcessDao processDao;
	@Autowired
	PartsDetailDao partsDetailDao;
	@Autowired
	SapPartsService sapPartsService;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			queryMap.put("updateId", sysUser.getUserid());
		}
		List<PartsModel> list = partsDao.selectList(queryMap);
		int count = partsDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 *
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String parId) {
		HttpResult httpResult = new HttpResult();
		PartsModel partsModel = partsDao.load(parId);
		Map<String, Object> params = new HashMap<>();
		params.put("parId", parId);
		List<ProcessModel> processes = processDao.selectList(params);
		partsModel.setProcesses(processes);
		httpResult.setData(partsModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public HttpResult save(PartsModel partsModel) {
		if (partsModel == null) {
			return HttpResult.error("参数不能为空");
		}
		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = partsDao.update(partsModel);
		if (result > 0) {
			List<ProcessModel> process = partsModel.getProcesses();
			if (!CollectionUtils.isEmpty(process)) {
				for (ProcessModel processModel : process) {
					// result = processDao.update(processModel);
					// if (result > 0) {
					List<PartsDetailModel> partsDetails = processModel.getPartsDetailModels();
					if (!CollectionUtils.isEmpty(partsDetails)) {
						for (PartsDetailModel partsDetailModel : partsDetails) {
							result = partsDetailDao.update(partsDetailModel);
						}
					}
					// }
				}

			}

		}

		if (result > 0) {
			httpResult.setMsg(partsModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(partsModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(partsModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public HttpResult commit(PartsModel partsModelTem) throws ServerException {
		if (null == partsModelTem) {
			throw new ServerException("参数不得为空");
		}
		Map<String, Object> params = new HashMap<>();
		String parId = partsModelTem.getParId();
		int result = 0;
		result = partsDao.update(partsModelTem);
		if (result == 0) {
			throw new ServerException("保存失败");
		}
		// 提交

		PartsModel partsModel = partsDao.load(parId);
		params.put("parId", parId);
		List<ProcessModel> list = processDao.selectList(params);
		if (!CollectionUtils.isEmpty(list)) {
			for (ProcessModel processModel : list) {
				Map params1 = new HashMap();
				params.put("parId", parId);
				params.put("procId", processModel.getProcId());
				List<PartsDetailModel> partDetails = partsDetailDao.selectList(params);
				processModel.setPartsDetailModels(partDetails);
			}
		}
		partsModel.setProcesses(list);
		// 调用SAP接口
		if (partsModel.getStatus().equals(Global.YES + "")) {
			HttpResult sapHttpResult = sapPartsService.partsDataToSAP(partsModel);
			if (sapHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
				// 强制手动事务回滚
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error("SAP系统回执:" + sapHttpResult.getMsg());
			}
		}
		return HttpResult.ok("操作成功");
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String parId) {
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(parId)) {
			return HttpResult.error("参数不能为空");
		}
		int result = partsDao.delete(parId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 *
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<PartsModel> list = partsDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), PartsModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
